const fs = require('fs');
const util = require('util');
const join = require('path').join;

const getFolderFiles = (folderPath,fileTypes=[]) => {
	/*
	读取文件夹内所有某类型文件路径
	*/
	let arr = [];
	const files = fs.readdirSync(folderPath);
	files.forEach(function (item, index) {
	    let fPath = join(folderPath,item);
	    let stat = fs.statSync(fPath);
	    if(stat.isDirectory() === true) {
	        arr = arr.concat(getFolderFiles(fPath,fileTypes));
	    }
	    if (stat.isFile() === true) {
	      arr.push(fPath);
	    }
	});
	return arr;
}
const fileIsExist = (file) => {
	// 文件是否存在
	return new Promise((ok, fail) => {
		fs.access(file, fs.constants.F_OK, (err) => {
			ok(!err);
		});
	})
}
const fileIsReadable = (file) => {
	// 文件是否可读
	return new Promise((ok, fail) => {
		fs.access(file, fs.constants.R_OK, (err) => {
			ok(!err);
		});
	})
}
const fileIsWriteable = file => {
	// 文件是否可写
	return new Promise((ok, fail) => {
		fs.access(file, fs.constants.W_OK, (err) => {
			ok(!err);
		});
	})
}
const pathType = async (path) => {
	// 判断路径类型
	const stats = await util.promisify(fs.stat)(path);
	return {
		file: stats.isFile(),
		directory: stats.isDirectory(),
	}
}
const getFileData = (filePath,opts={}) => {
	const data = fs.readFileSync(filePath, { encoding: 'utf-8' ,...opts});
	return data;
}

const fileWriteTo = (path, fileData) => {
	const r = fs.writeFileSync(path, fileData, {});
	return !r;
}

module.exports = {
	getFolderFiles,
	getFileData,
	fileWriteTo,
}
